/*
 * BackwardValidationAgent.java   ver    9 Nov 2009
 * 
 * Copyright (c) 2009 mentalsmash.org
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The use of the Apache License does not indicate that this project is
 * affiliated with the Apache Software Foundation.
 */
package org.mentalsmash.tazio.transactions.control.impl;

import java.util.List;
import java.util.Set;

import org.mentalsmash.tazio.transactions.control.SystemTransactionManager;
import org.mentalsmash.tazio.transactions.control.TazioTransaction;
import org.mentalsmash.tazio.transactions.control.TransactionsLog;
import org.mentalsmash.tazio.transactions.control.ValidationAgent;
import org.mentalsmash.tazio.transactions.model.identifiers.OID;

import com.google.common.collect.Sets;
import com.google.inject.Inject;

/**
 * @author Andrea Reale
 * @version 0.0.1
 */
public class BackwardValidationAgent implements ValidationAgent {

    private final TransactionsLog txLog;

    /**
     * Create a new instance of <tt>BackwardValidationAgent</tt> that will use
     * the provided {@link SystemTransactionManager}
     * 
     * @param tm
     *            the {@link SystemTransactinoManager} instance that manages
     *            transactions on the node were the <tt>ValidationAgent</tt>
     *            will operate
     */
    @Inject
    BackwardValidationAgent(final TransactionsLog log) {
	this.txLog = log;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.transactions.impl.ValidationAgent#validate(org.
     * mentalsmash.tazio.transactions.impl.TazioTransaction)
     */
    @Override
    public boolean validate(final TazioTransaction tx) {
	final long initialSeqNo = tx.getSeqNo();

	// retrieves the list of transaction that were committed after tx
	// started
	final List<TazioTransaction> potentialConflicts = this.txLog
		.getCommitted(initialSeqNo + 1, -1);

	// checks whether no transaction that started after tx has written stuff
	// that tx has read
	for (final TazioTransaction committed : potentialConflicts) {
	    final Set<OID> commitedWS = committed.getWriteSet();
	    final Set<OID> thisRS = tx.getReadSet();

	    if (!Sets.intersection(thisRS, commitedWS).isEmpty()) {
		return false;
	    }
	}

	return true;
    }

}
